package com.sz.zhiling.common;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpClientUtils {
    public static String getMethod(String url){
        String result=null;
        HttpClient httpClient=HttpClients.createDefault();
        HttpGet httpGet=new HttpGet(url);
        try {
            HttpResponse httpResponse=httpClient.execute(httpGet);
            HttpEntity entity=httpResponse.getEntity();
            result=EntityUtils.toString(entity,"utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            httpGet.releaseConnection();
        }
        return result;
    }
    public static String postMethod(String url,String json){
        String result=null;
        HttpClient httpClient=HttpClients.createDefault();
        HttpPost post=new HttpPost(url);
        StringEntity stringEntity=new StringEntity(json,"utf-8");
        post.setHeader("content-type","application/json;charset=utf-8");
        post.setEntity(stringEntity);
        try {
            HttpResponse response=httpClient.execute(post);
            HttpEntity entity=response.getEntity();
            result=EntityUtils.toString(entity,"utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            post.releaseConnection();
        }
        return result;
    }
}
